#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "config.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("局域网文件传输管理工具(客户端)");
    this->setFixedSize(WINDOW_WIDTH,WINDOW_HEIGHT);
    this->setWindowIcon(QIcon(WINDOWS_ICO_PATH));
    pic.load(BACK_PATH);
    Initialize();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::Initialize()
{
    TCPSocket = new QTcpSocket();
    this->isconnection=false;
    ui->slot_disconnect->setEnabled(false);

    //成功连接服务器的connected()信号连接到slot_connected() (注意：不是connect()信号)
    connect(TCPSocket,SIGNAL(connected()),this,SLOT(slot_connected()));
    //发送按钮的clicked()信号连接到slot_sendmessage()
    connect(ui->pushButton_send,SIGNAL(clicked()),this,SLOT(slot_sendmessage()));
    //有新数据到达时的readyread()信号连接到slot_recvmessage()
    connect(TCPSocket,SIGNAL(readyRead()),this,SLOT(slot_recvmessage()));
    //与服务器断开连接的disconnected()信号连接到slot_disconnect()
    connect(TCPSocket,SIGNAL(disconnected()),this,SLOT(slot_disconnect()));
}

void MainWindow::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawPixmap(0,0,pic);
}

void MainWindow::on_link_clicked()
{
    QString IP = ui->EditIP->text();
    qint16 Port = ui->EditPort->text().toInt();
    //终止之前的连接，重置套接字
    TCPSocket->abort();

    //给定IP和端口号，连接服务器
    TCPSocket->connectToHost(QHostAddress(IP), Port);
    this->isconnection = TCPSocket->waitForConnected();
    this->ui->link->isFlat();
}

void MainWindow::slot_connected()
{
    this->isconnection=true;
    ui->label_3->setText("已连接服务器端");
    ui->slot_disconnect->setEnabled(true);
    ui->link->setEnabled(false);
    QMessageBox::information(this, "QT网络通信", "服务器端连接成功！");
}

void MainWindow::slot_sendmessage()
{
    if(this->isconnection)
    {
        QString sendMessage = ui->lineEdit->text(); //从单行文本框获得要发送消息
        if(!sendMessage.isEmpty())
        {
            //发送消息到服务器
             this->TCPSocket->write(sendMessage.toLatin1());
//             int sendRe = this->TCPSocket->write(sendMessage.toLatin1());
//            bool falg= this->TCPSocket->flush();
//            qDebug()<<falg;
//            int bpps= this->TCPSocket->waitForConnected(123);
//            qDebug()<<bpps;
//            this->TCPSocket->waitForBytesWritten();
            //本地显示发送的消息
            QString localDispalyMessage = tr("send to server: ") + sendMessage \
                                            + QDateTime::currentDateTime().toString(" yyyy-M-dd hh:mm:ss") + tr("\n");
            ui->textBrowser->append(localDispalyMessage);
        }
        else
            QMessageBox::warning(this,"错误","消息不能为空!",QMessageBox::Ok);
    }
    else
        QMessageBox::warning(this,"错误","未连接到服务器!",QMessageBox::Ok);

    ui->lineEdit->clear();
}

void MainWindow::slot_recvmessage()
{
    QMessageBox::information(this, "QT网络通信", "有新消息！");
    //接收来自服务器的消息
    QByteArray byteArray = this->TCPSocket->readAll();
    QString recvMessage = tr("recv from server: ") + byteArray + QDateTime::currentDateTime().toString(" yyyy-M-dd hh:mm:ss\n") + tr("\n");
    ui->textBrowser->append(recvMessage);
}

void MainWindow::slot_disconnect()
{
    if(TCPSocket != nullptr&&this->isconnection)
    {
        this->isconnection=false;
        ui->textBrowser->append("连接断开!");
        TCPSocket->disconnectFromHost();
        QMessageBox::information(this, "QT网络通信", "断开与服务端的连接！");
        ui->slot_disconnect->setEnabled(false);
        ui->link->setEnabled(true);
        ui->label_3->setText("未连接服务器");
     //   TCPSocket->close(); //关闭客户端
      //  TCPSocket->deleteLater();//deletelater的原理是 QObject::deleteLater()并没有将对象立即销毁，而是向主消息循环发送了一个event，下一次主消息循环收到这个event之后才会销毁对象。
    }
}

void MainWindow::on_pushButton_2_clicked()
{
    ui->textBrowser->clear();
}

void MainWindow::on_slot_disconnect_clicked()
{
   slot_disconnect();
//   TCPSocket = new QTcpSocket();
}

void MainWindow::on_pushButton_3_clicked()
{
    this->close();
}

